<template>
  <div>
    <div class="top">
      <el-select v-model="all" placeholder="选择种类" filterable>
        <el-option
          label="所有"
          value="company"
        />
        <el-option
          label="我创建的"
          value="mine"
        />
        <el-option
          label="系统创建"
          value="system"
        />
      </el-select>
      <el-select v-model="app" placeholder="使用场景" filterable clearable>

        <el-option
          v-for="category in apps"
          :key="category.label"
          :label="category.label"
          :value="category.value"
        />
      </el-select>
      <el-select v-model="project_id" placeholder="选择项目" filterable clearable>
        <el-option value="" label="所有" />
        <el-option
          v-for="item in projects"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-input
        v-model="kwInput"
        placeholder="输入 任意字符 进行筛选"
        class="input-with-select"
        clearable
        style="width: 300px;"
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加')"
      >添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="handleSort"
    >

      <el-table-column align="center" width="500" label="基本信息" fixed="left">
        <el-table-column align="center" width="80" prop="id" label="ID" sortable="custom" />
        <el-table-column align="center" label="名称" prop="name" sortable="custom" width="100">
          <template slot-scope="scope">
            <span :title="scope.row.name">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="公司" prop="project_id" sortable="custom" width="100">
          <template slot-scope="scope">
            <span :title="scope.row.project_name">{{ scope.row.project_name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="性质" prop="is_rule" sortable="custom" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.global_public" type="danger">系统预设</el-tag>
            <el-tag v-else-if="scope.row.company_public" type="success">公司公共</el-tag>
            <el-tag v-else>个人</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用于" prop="app" sortable="custom" width="120">
          <template slot-scope="scope">
            <span :title="scope.row.app">{{ scope.row.app }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column align="center" label="使用次数" prop="use_count" sortable="custom" width="120" />
      <el-table-column align="center" label="模型" prop="engine" sortable="custom" width="120">
        <template slot-scope="scope">
          <el-select v-model="scope.row.engine" @change="handleEditRow(scope.row)">
            <el-option
              v-for="item in ai_engines"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="全局规则" prop="is_rule" sortable="custom" width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_rule"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="隐藏" prop="is_hidden" sortable="custom" width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_hidden"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </template>
      </el-table-column>

      <el-table-column align="center" label="prompt" prop="prompt" sortable="custom">
        <template slot-scope="scope">
          <div class="prompt-cell">
            <div v-if="editingPromptId === scope.row.id" class="prompt-editor-container">
              <v-md-editor
                v-model="scope.row.prompt"
                height="300px"
                left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code"
                right-toolbar="preview fullscreen"
              />
              <div class="prompt-actions">
                <el-button size="mini" type="success" @click="savePromptEdit(scope.row)">保存</el-button>
                <el-button size="mini" @click="cancelPromptEdit">取消</el-button>
              </div>
            </div>
            <div v-else class="prompt-preview-container">
              <v-md-editor
                v-model="scope.row.prompt"
                mode="preview"
                height="150px"
              />
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                class="edit-prompt-btn"
                @click="startPromptEdit(scope.row)"
              >
                编辑 Markdown
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="400" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleAction('copy', scope.row)">复制</el-button>
          <el-button size="mini" type="warning" @click="handleAction('shortcode', scope.row)">ShortCode</el-button>
          <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="80px">

        <el-form-item v-if="action !== 'delete'" label="名称">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="提示">
          <el-input v-model="temp.placeholder" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="prompt">
          <v-md-editor
            v-model="temp.prompt"
            height="400px"
            left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code"
            right-toolbar="preview fullscreen"
            placeholder="请输入 prompt 内容，支持 Markdown 语法"
          />
          <div class="prompt-hint">
            <i class="el-icon-info" />
            支持 Markdown 语法：标题、加粗、斜体、列表、代码块、链接等
          </div>
        </el-form-item>
        <el-form-item v-model="temp.project_id">
          <el-select v-model="temp.project_id" placeholder="选择公司(不选则为全局)" filterable clearable>
            <el-option value="" label="系统" />
            <el-option
              v-for="item in projects"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="默认模型">
          <el-select v-model="temp.engine">
            <el-option
              v-for="item in ai_engines"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="全局规则">
          <el-switch v-model="temp.is_rule" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="应用于">
          <el-select v-model="temp.app" placeholder="应用于" class="head" filterable>
            <el-option
              v-for="category in apps"
              :key="category.label"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!temp.global_public" label="公司公共">
          <el-switch
            v-model="temp.company_public"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="系统参数">
          <el-switch
            v-model="temp.global_public"
            active-color="#13ce66"
            :disabled="this.$store.getters.roles.indexOf('super_admin') === -1"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="隐藏">
          <el-switch
            v-model="temp.is_hidden"
            active-color="#13ce66"
            :disabled="this.$store.getters.roles.indexOf('super_admin') === -1"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      append-to-body
      :title="'ShortCode'"
      :visible.sync="shortcodeVisible"
      @close="shortcodeVisible = false"
    >
      使用模型:<el-select v-model="engine" placeholder=" " size="mini" filterable clearable @change="handleGenerateShortCode">
        <el-option v-for="item in ai_engines" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-input v-model="showrt_code" :rows="5" placeholder="shortcode" />
      <el-button type="primary" @click="copyShortCode">复制</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/cms/aiprompt'
import { Get as GetAllProjects } from '@/api/erp/elicink/project.js'

import qs from 'qs'
import { aiprompt_apps } from '../../api/crm/crmcommon'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Promptsmanage',
  data() {
    return {
      ai_engines: [
        {
          label: 'GTP3.5',
          value: 'gpt-3.5-turbo'
        },
        {
          label: '通义千问',
          value: 'qwen_turbo'
        },
        {
          label: 'GTP 4(很贵,慎用)',
          value: 'gpt-4'
        }
      ],
      data: [],
      app: '',
      engine: 'gpt-4o',
      showrt_code: '',
      listLoading: true,
      all: 'company',
      kwInput: '',
      project_id: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      shortcodeVisible: false,
      action: null,
      dialogVisible: false,
      title: '',
      projects: [],
      temp: {
        name: '',
        placeholder: '请输入额外要求',
        project_id: '',
        is_hidden: false,
        is_rule: false,
        use_count: 0,
        prompt: '',
        engine: 'gpt-4o',
        app: '',
        company_public: true,
        global_public: false
      },
      apps: aiprompt_apps,
      width: '',

      innerDialogVisible: false,
      editingPromptId: null, // 当前正在编辑的 prompt ID
      originalPrompt: '' // 保存原始 prompt 内容，用于取消编辑
    }
  },
  created() {
    this.handleGetAllProjects()
    this.getList()
  },
  methods: {
    handleGetAllProjects() {
      GetAllProjects().then(response => {
        this.projects = response.data.data
      })
    },
    copyShortCode() {
      this.$copyText(this.showrt_code).then(() => {
        this.$message({
          message: '复制成功',
          type: 'success'
        })
        this.shortcodeVisible = false
        this.$emit('insert', this.showrt_code)
      }, () => {
        this.$message({
          message: '复制失败',
          type: 'error'
        })
      })
    },
    handleGenerateShortCode(v) {
      this.showrt_code = `[aiwriter engine="${v}" id="${this.temp.id}" name="${this.temp.name}"]`
    },
    resetTemp() {
      this.temp = {
        name: '',
        project_id: '',
        prompt: '',
        is_rule: false,
        placeholder: '请输入额外要求',
        app: '',
        use_count: 0,
        engine: 'gpt-4o',
        company_public: true,
        global_public: false
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        all: this.all,
        app: this.app,
        project_id: this.project_id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
          this.ai_engines = response.data.ai_engines
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleEditRow(row) {
      // 检查数据合法性
      if (row.id === '' || row.id === undefined || row.prompt === '') {
        this.$message({
          message: '请填写完整',
          type: 'error'
        })
        return
      }
      Put(row.id, row).then((response) => {
        this.notify('更新成功')
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'copy':
          this.resetTemp()
          this.temp.use_count = 0
          this.temp.name = row.name
          this.temp.prompt = row.prompt
          this.temp.is_rule = row.is_rule
          this.temp.is_hidden = row.is_hidden
          this.temp.app = row.app
          this.temp.public = row.public
          this.action = 'create'
          this.innerDialogVisible = true
          break
        case 'shortcode':
          this.temp = row
          this.shortcodeVisible = true
          this.handleGenerateShortCode(this.engine)
          break
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.name}?`
          this.temp = row
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${row.name}`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(this.temp).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case 'delete':
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case 'edit':
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeDialog', false)
    },
    // Markdown 编辑相关方法
    startPromptEdit(row) {
      this.editingPromptId = row.id
      this.originalPrompt = row.prompt
    },
    savePromptEdit(row) {
      // 保存编辑
      this.handleEditRow(row)
      this.editingPromptId = null
      this.originalPrompt = ''
    },
    cancelPromptEdit() {
      // 取消编辑，恢复原始内容
      if (this.editingPromptId) {
        const row = this.data.find(item => item.id === this.editingPromptId)
        if (row) {
          row.prompt = this.originalPrompt
        }
      }
      this.editingPromptId = null
      this.originalPrompt = ''
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin-top: 60px;
    /*margin: 168px auto !important;*/
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
  }

  /* Markdown 编辑器相关样式 */
  .prompt-cell {
    width: 100%;
    min-height: 150px;
  }

  .prompt-editor-container {
    width: 100%;
  }

  .prompt-actions {
    margin-top: 10px;
    text-align: right;
  }

  .prompt-actions .el-button {
    margin-left: 10px;
  }

  .prompt-preview-container {
    position: relative;
    width: 100%;
  }

  .edit-prompt-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    z-index: 10;
    background: rgba(255, 255, 255, 0.9);
    padding: 5px 10px;
    border-radius: 4px;
  }

  .edit-prompt-btn:hover {
    background: rgba(255, 255, 255, 1);
    color: #409EFF;
  }

  .prompt-hint {
    margin-top: 8px;
    color: #909399;
    font-size: 12px;
  }

  .prompt-hint i {
    margin-right: 4px;
  }

  /* 自定义 v-md-editor 样式 */
  >>> .v-md-editor {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
  }

  >>> .v-md-editor__toolbar {
    border-bottom: 1px solid #DCDFE6;
    background-color: #f5f7fa;
  }

  >>> .v-md-editor__toolbar-item {
    color: #606266;
  }

  >>> .v-md-editor__toolbar-item:hover {
    color: #409EFF;
    background-color: #ecf5ff;
  }

  >>> .v-md-editor__preview {
    padding: 15px;
  }

  >>> .v-md-editor__preview h1,
  >>> .v-md-editor__preview h2,
  >>> .v-md-editor__preview h3 {
    margin-top: 1em;
    margin-bottom: 0.5em;
    color: #303133;
  }

  >>> .v-md-editor__preview code {
    background-color: #f5f7fa;
    padding: 2px 6px;
    border-radius: 3px;
    color: #e83e8c;
  }

  >>> .v-md-editor__preview pre {
    background-color: #282c34;
    border-radius: 4px;
    padding: 15px;
  }

  >>> .v-md-editor__preview pre code {
    background-color: transparent;
    color: #abb2bf;
  }
</style>
